package com.hyy.blogtest.common.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Slf4j
public class JwtUtil {
    public static String secret = "pI/zFLQyi79frWug+DOOVyX0OYb+v5ZBbTAywDZx4vk=";
    public static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));


    //有效期7天
    private static final long expiration = 1000 * 60 * 60 * 24 * 7L;

    public static String getToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)//设置键值对
                .setIssuedAt(new Date())//签发日期
                .signWith(key)//添加签名，这样不知道解密密钥的情况下，就无法解析token
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .compact();//compact是构建一个紧凑的字符串
    }

    public static Claims parseToken(String token) {

        try{
            //根据key创建解析器
            JwtParser builder = Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build();

            //用解析器，解析token，获取body
            Claims claims = builder.parseClaimsJws(token).getBody();
            return claims;
        }catch (ExpiredJwtException e){
            log.error("令牌过期了：{}", e.getMessage());
        }catch (SignatureException e){
            log.error("签名不匹配：{}",e.getMessage());
        }catch (Exception e) {
            log.error("其他解析异常：{}",e.getMessage());
        }
        return null;
    }

    public String getSecret(){
        SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        String enCode= Encoders.BASE64.encode(key.getEncoded());
        return enCode;
    }
}
